package com.dunqi.gpm.shunqing.home.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.PhotoPreviewActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.foamtrace.photopicker.intent.PhotoPreviewIntent;
import com.nanchen.compresshelper.CompressHelper;
import com.dunqi.gpm.shunqing.R;
import com.dunqi.gpm.shunqing.common.api.ApiFactory;
import com.dunqi.gpm.shunqing.common.api.RxSchedulers;
import com.dunqi.gpm.shunqing.common.base.BaseAct;
import com.dunqi.gpm.shunqing.common.base.Data;
import com.dunqi.gpm.shunqing.common.util.FormUtil;
import com.dunqi.gpm.shunqing.common.util.JsonUtils;
import com.dunqi.gpm.shunqing.common.util.RequestBodyUtil;
import com.dunqi.gpm.shunqing.common.util.TimeUtil;
import com.dunqi.gpm.shunqing.common.view.ComTitleBar;
import com.dunqi.gpm.shunqing.common.view.NoScrollGridView;
import com.dunqi.gpm.shunqing.home.adapter.PhotoAdapter;
import com.dunqi.gpm.shunqing.home.constance.Constance;
import com.dunqi.gpm.shunqing.home.widget.DatePickerDiaglog;
import com.dunqi.gpm.shunqing.home.widget.NormalView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;

public class CompleteEarlyInfoActivity extends BaseAct implements AdapterView.OnItemClickListener {

    private static final String PROANNUALPLANPRESTAGEID = "proannualplanprestageid";
    private static final String NAME = "name";
    @BindView(R.id.title_bar)
    ComTitleBar titleBar;
    @BindView(R.id.name_view)
    NormalView nameView;
    @BindView(R.id.time_tv)
    TextView timeTv;
    @BindView(R.id.config_btn)
    TextView config_btn;

    @BindView(R.id.question_edit)
    EditText questionEdit;
    @BindView(R.id.remark_edit)
    EditText remarkEdit;
    @BindView(R.id.grid_view)
    NoScrollGridView gridView;

    ArrayList<String> data = new ArrayList<>();
    private PhotoAdapter adapter;

    String actureStartTime;
    private long proannualPlanprestageId;
    private String name;

    @Override
    protected void refreshData(Bundle savedInstanceState) {

    }

    @Override
    protected void initUiAndListener() {
        proannualPlanprestageId = getIntent().getLongExtra(PROANNUALPLANPRESTAGEID, 0);
        name = getIntent().getStringExtra(NAME);

        data.add(null);
        adapter = new PhotoAdapter(getActivity(), data);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(this);

        actureStartTime = TimeUtil.getCurrentTimeTen();
        timeTv.setText(actureStartTime);
        nameView.setText(name);

        config_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commit();
            }
        });


    }

    private void commit() {

        ArrayList<String> photos = getPhotos();

        if (photos.isEmpty()) {
            t("至少添加一张图片");
            return;
        }
        HashMap<String, String> param = new HashMap<>();

        param.put("proAnnualPlanPreStageId", String.valueOf(proannualPlanprestageId));
        param.put("actualCompleteTime", actureStartTime);
        param.put("existedProblem", getQuestiontext());

        String[] remarks = new String[photos.size()];
        for (int i = 0; i < photos.size(); i++) {
            remarks[i] = getRemarkText();
        }

//        actualCompleteTime
//                proAnnualPlanPreStageId
//        existedProblem
//                remark

        param.put("fileRemark", JsonUtils.toJson(remarks));
        param.put("remark", getRemarkText());

        HashMap<String, RequestBody> bodyHashMap = FormUtil.AddHeader(param);

        for (String photo : photos) {
            File file = CompressHelper.getDefault(this)
                    .compressToFile(new File(photo));
            bodyHashMap.put("stage-file\"; filename=\"" + file.getName(), RequestBodyUtil.get(file));
        }

        final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在提交...");
        ApiFactory.getInstance()
                .completeStage(bodyHashMap)
                .compose(RxSchedulers.<Data>io_main())
                .subscribe(new Consumer<Data>() {
                    @Override
                    public void accept(Data data) throws Exception {
                        dialog.dismiss();
                        setResult(365);
                        finish();
                        t("提交成功");
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dialog.dismiss();
                        t("提交失败");
                    }
                });


    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_complete_early_info;
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String path = data.get(position);

        if (TextUtils.isEmpty(path)) {
            PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true); // 是否显示拍照， 默认false
            intent.setMaxTotal(Constance.MAX_PIC); // 最多选择照片数量，默认为9
            ArrayList<String> paths = getPhotos();
            intent.setSelectedPaths(paths); // 已选中的照片地址， 用于回显选中状态
            // intent.setImageConfig(config);
            startActivityForResult(intent, Constance.REQUEST_CAMERA_CODE);
        } else {
            PhotoPreviewIntent intent = new PhotoPreviewIntent(getActivity());
            intent.setCurrentItem(position - 1); // 当前选中照片的下标
            ArrayList<String> paths = getPhotos();
            intent.setPhotoPaths(paths); // 已选中的照片地址
            startActivityForResult(intent, Constance.REQUEST_PREVIEW_CODE);
        }
    }

    @NonNull
    private ArrayList<String> getPhotos() {
        ArrayList<String> paths = new ArrayList<>();
        paths.addAll(data);
        paths.remove(0);
        return paths;
    }

    public String getQuestiontext() {
        return questionEdit.getText().toString().trim();
    }

    public String getRemarkText() {
        return remarkEdit.getText().toString().trim();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case Constance.REQUEST_CAMERA_CODE:
                    refreshAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                    break;
                // 预览
                case Constance.REQUEST_PREVIEW_CODE:
                    refreshAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));
                    break;
//            }
            }
        }
    }

    private void refreshAdpater(ArrayList<String> paths) {
        // 处理返回照片地址
        data.clear();
        data.add(null);
        data.addAll(paths);
        adapter.notifyDataSetChanged();
    }

    @OnClick(R.id.time_tv)
    public void onViewClicked() {
        final DatePickerDiaglog diaglog = new DatePickerDiaglog(getActivity());
        diaglog.show();
        diaglog.setCanceledOnTouchOutside(true);
        diaglog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                actureStartTime = diaglog.getTime();
                timeTv.setText(actureStartTime);
            }
        });
    }

    public static void start(Activity context, long proAnnualPlanPreStageId, String name) {
        Intent intent = new Intent(context, CompleteEarlyInfoActivity.class);
        intent.putExtra(PROANNUALPLANPRESTAGEID, proAnnualPlanPreStageId);
        intent.putExtra(NAME, name);
        context.startActivityForResult(intent, 594);
    }

}
